
function getPlateNumToken() {
  var localPlateNumToken = localStorage.getItem("plateToken")

  if (!localPlateNumToken) {
    localStorage.setItem("plateToken","24.6eff1b005473252b8816d968b62504ce.2592000.1538015509.282335-11736463"+"time="+new Date().getTime())

    platetoken()
  } else {
    var time = localPlateNumToken.split("time=")[1]
    if (new Date().getTime() - time > 20 * 24 * 3600 * 1000) {
      localStorage.removeItem("plateToken")
      platetoken()
    }
  }
  // console.log("get token")
}

// 获取文字识别授权
function platetoken() {
  var grant_type = "client_credentials"
  var client_id = "gvtvAWjh7N8dzp5ks775tU8l"; //apiKey
  var client_secret = "fBvnEtwYHxC4O55iy4plaMDrCzVsIbqU "; //secretkey
  var url = "http://aip.baidubce.com/oauth/2.0/token?grant_type=" + grant_type + "&client_id=" + client_id + "&client_secret=" + client_secret
  $axios.post(url).then(res => {
    var token = res.data.access_token + "time=" + new Date().getTime()
    localStorage.setItem("plateToken", token)
  })
}

function plate(img,result) {
  var params = {
    image:UrlEncode(img),
    // multi_detect: false,
    accuracy:"",//是否使用高精度
  }
  // var url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=" //通用类文字识别
  // var url = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=" //车牌识别

  var token = localStorage.getItem("plateToken").split("time=")[0]

  var url="/baiduapi"+(result.general?"vehicle_license":"license_plate")+"?access_token=" + token //本地调试
  var url0=(result.general?"https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license?access_token=":"https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=")+token// 上线
  var url=_store.state.wxtoken.local?url:url0
  $.ajax({
    type: "post",
    url:url,
    dataType: "json",
    data: params,
    headers: { 'contentType': 'application/x-www-form-urlencoded' },
    success: function (data) {
        _store.state.dialogs.loading.show=false
        if(data.error_msg){
          _store.state.dialogs.alert.show=true
          _store.state.dialogs.alert.content=JSON.stringify(result.general?"请使用行驶证照片":data.error_msg)
        }
        result.number=result.general?data.words_result['车辆识别代号'].words:data.words_result.number
        _g.toMessage({status:'0',msg:"识别成功"})
    },
    error: function (data) { 
      _store.state.dialogs.loading.show=false
      _g.toMessage({status:'1',msg:"识别失败"})
    },
  });
}

async function getWords(img,result) {
  await getPlateNumToken()
  await plate(img,result)
}

function UrlEncode(str) {
  // return str
  var head = str.slice(0, 23)
  var str = str.slice(23)
  return str
  return head + str.replace(/\=/g, "%3D").replace(/\+/g, "%2B")
}


var appId=""
var secret=""
// 微信
function wxToken(){
  if(!localStorage.getItem("wx_token")){
    var path=(_store.state.wxtoken.local?"/wxapi/":"https://api.weixin.qq.com/cgi-bin/")+"token?grant_type=client_credential&appid="+appId+"&secret="+secret;
    return $axios.get(path).then(res=>{
      if(res.data.expires_in){
        localStorage.setItem("wx_token",res.data.access_token+'time='+new Date().getTime())
        return res.data.access_token
      }
    })
  }else{
    // 验证超时
    var time=localStorage.getItem("wx_token").split("time=")[1]
    if((new Date().getTime()-time)>720000){
      localStorage.removeItem("wx_token")
      return wxToken()
    }else{
      return localStorage.getItem("wx_token").split("time=")[0]
    }
  }
}

// 微信 sign
function wxSign(){
  var token=wxToken()
  var path=(_store.state.wxtoken.local?"/wxapi/":"https://api.weixin.qq.com/cgi-bin/")+"ticket/getticket?access_token="+token+"&type=jsapi"
  $axios.get(path).then(res=>{
    if(res.data.errcode==0){
      wxConfig(res.data.ticket)
    }
  })
}

function wxConfig(ticket){
  var timestamp=new Date().getTime()
  var obj={
    noncestr:"aSaSaSaSaSaS",
    jsapi_ticket:ticket,
    timestamp:timestamp,
    url:"http://mp.weixin.qq.com?params=value"
  }
  toString(obj)
}

function toString(obj){
  var str=""
  for(var key in obj){
    str+="&"+key+"="+obj[key]
  }
  wx.config({
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: appId, // 必填，公众号的唯一标识
    timestamp:obj.timestamp , // 必填，生成签名的时间戳
    nonceStr: obj.noncestr, // 必填，生成签名的随机串
    signature: hex_sha1(str.slice(1)),// 必填，签名
    jsApiList: ["updateTimelineShareData","getLocation"] // 必填，需要使用的JS接口列表
  });
}

// 微信用户授权
/**
 * @name wxUserInfo
 * @param {*} url 默认跳转地址
 * @param {*} id 卡券id换取appid和organizationId
 */
function wxUserInfo(url,id){
  // sessionStorage.setItem("logined",true)
  var redirecturl=url||(backPath+"homepage?id="+location.href.split("?id=")[1])
  var appidUrl=""
  if(!url){
    appidUrl="Appuser/getOrganInfo.do"
    localStorage.setItem("orgId",location.href.split("?id=")[1].split("&")[0])
    if(!location.href.split("?id=")[1].split("&")[0]){
      _g.toMessage({status:1,msg:"没有配置organizationId"})
    }
    _g.apiPost(appidUrl,{organizationId:location.href.split("?id=")[1].split("&")[0]}).then(res=>{
      appId=res.data.appid
    }).then(()=>{
      var path="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+redirecturl+"&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
      location.href=path
    })
  }else{
    appidUrl="couponApp/getCouponOrgan.do"
    _g.apiPost(appidUrl,{id}).then(res=>{
      appId=res.data.appid
      sessionStorage.setItem("appId",appId)
      sessionStorage.setItem("organizationId",res.data.id)
    }).then(()=>{
      var path="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+redirecturl+"&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
      location.href=path
    })
  }
}

/**
 * @name getCode
 * @param {*} bool 是否调用正常登录接口
 */
function getCode(bool){
  if(location.href.indexOf("?id=")>-1){
    localStorage.setItem("orgId",location.href.split("?id=")[1].split("&")[0])
    var code=location.href.split("code=")[1].split("&")[0]
    var params={
      code,
      organizationId:localStorage.getItem("orgId")
    }
    if(!bool)_g.login(params)
    sessionStorage.setItem("myCode",code)
  }else if(location.href.indexOf("/member/voucher/shareInfo/")>-1){
    sessionStorage.setItem("myCode",location.href.split("code=")[1].split("&")[0])
  }else if(!sessionStorage.getItem("myCode")){
    getCode(bool)
  }
}

export { getWords,wxToken,wxSign,wxUserInfo,getCode,wxConfig}